#include "BF.h"
#include "Sorted_GetAllEntries.h"

int Sorted_GetAllEntries( int fileDesc, char* fieldName, void* value ){


	void* block;
	int numberOfBlocks; 
	int blockIndex = 0;
	int recordsNum;	
	Record currentRecord;
	int recordIndex = 0;
	char* pointer;


	currentRecord = malloc(sizeof(Record);


	/*getting number of blocks*/
	if( ( numberOfBlocks = BF_GetBlockCounter(fileDesc) ) < 0 ){
		BF_PrintError("Cannot Get Block Counter");
		return -1;
	}

	/*looping through the blocks of the file*/
	for( blockIndex ; blockIndex < numberOfBlocks ; blockIndex++  ){
		
		if( BF_ReadBlock(fileDesc, blockIndex, &block) < 0 ){
			BF_PrintError("Cannot Read Block");
			return -1;
		}

		/*getting the number of records of the block*/
		memcpy( &recordsNum, block, sizeof(int) );

		/*for each record we check the field name and the value*/
		for( recordIndex ; recordIndex < recordsNum ; recordIndex++ ){

			/*getting the contents of each record of the block*/
			pointer = block+sizeof(int)+recordIndex*sizeof(Record);
			memcpy( &currentRecord, pointer, sizeof(Record) );
			
			/*we check the value according to the fieldName input*/
			if( strcmp(fieldName,"id") ){
	
				/*if the record's value matches the input value we print it*/
				/*if not, we move to the next record*/
				if( currentRecord.id == value ){
					printf("{%d\t%s\t%s\t%f}",currentRecord.id,currentRecord.name,currentRecord.surname,currentRecord.avgPoints);
				}
				else continue;				
	
			}
			else if( strcmp(fieldName,"name") ){

				if( strcmp( currentRecord.name , value ) ){
					printf("{%d\t%s\t%s\t%f}",currentRecord.id,currentRecord.name,currentRecord.surname,currentRecord.avgPoints);
				}
				else continue;

			}
			else if( strcmp(fieldName,"surname") ){

				
				if( strcmp( currentRecord.name , value ) ){
					printf("{%d\t%s\t%s\t%f}",currentRecord.id,currentRecord.name,currentRecord.surname,currentRecord.avgPoints);
				}
				else continue;

			}
			else if( strcmp(fieldName,"avgPoints") ){

				if( currentRecord.avgPoints == value ) ){
					printf("{%d\t%s\t%s\t%f}",currentRecord.id,currentRecord.name,currentRecord.surname,currentRecord.avgPoints);
				}
				else continue;
			
			}
			else{
				printf("unidentified field name");
			}			

		}	
				

	}
	
	

	



}
